package com.bodu.member.client.impl;

import cn.hutool.core.util.ObjectUtil;
import com.bodu.core.entity.result.Result;
import com.bodu.core.util.WechatUtil;
import com.bodu.member.client.UserClient;
import com.bodu.member.entity.request.MemberUserRequest;
import com.bodu.member.entity.vo.MemberUserVo;
import com.bodu.member.service.MemberUserService;
import com.bodu.wxchat.entity.vo.WxchatMiniappConfigVo;
import com.bodu.wxchat.service.WxchatMiniappConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service("userClient")
public class UserClientImpl implements UserClient {

    @Autowired
    private MemberUserService memberUserService;

    @Autowired
    private WxchatMiniappConfigService wxchatMiniappConfigService;

    @Override
    public Result getWeixinOpenid(String jsCode) {
        WxchatMiniappConfigVo wxchatMiniappConfigVo = wxchatMiniappConfigService.getModelLimit1();
        Map<String, Object> wopid = WechatUtil.getOpenId(jsCode, wxchatMiniappConfigVo.getAppId(), wxchatMiniappConfigVo.getAppSecret());
        if (ObjectUtil.isEmpty(wopid) || wopid.size() == 0) {
            return Result.fail("没有获得openId信息");
        }
        return Result.success(wopid);
    }

    @Override
    public Result getUser(String openid) {
        MemberUserVo userVo = memberUserService.getModelByOpenId(openid);
        return Result.success(userVo);
    }

    @Override
    public Result saveUser(MemberUserRequest userRequest) {
        MemberUserVo userVo = memberUserService.getModelByOpenId(userRequest.getOpenId());
        if (ObjectUtil.isEmpty(userVo)) {
            Long saveCount = memberUserService.save(userRequest);
            return Result.success(saveCount);
        } else {
            return Result.success(userVo.getId());
        }
    }
}
